"use client"

import { useState, useRef, useEffect } from "react"
import { View, Text, StyleSheet, TouchableOpacity, Platform, StatusBar, ScrollView, Alert } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { ArrowLeft, BookmarkIcon } from "lucide-react-native"
import { useRouter, useLocalSearchParams } from "expo-router"
import { theme } from "../constants/theme"
import { LinearGradient } from "expo-linear-gradient"
import { GestureHandlerRootView } from "react-native-gesture-handler"
import BookshelfView from "../components/books/BookshelfView"
import LibraryContent from "../components/books/LibraryContent"
import AsyncStorage from "@react-native-async-storage/async-storage"

// 分类数据
const CATEGORIES = [
    { id: "hot", name: "热门" },
    { id: "primary", name: "小学" },
    { id: "junior", name: "初中" },
    { id: "senior", name: "高中" },
    { id: "college", name: "大学" },
    { id: "new", name: "新概念" },
    { id: "bridge", name: "剑桥" },
    { id: "exam", name: "考试" },
]

// 我的书架初始数据
const INITIAL_MY_BOOKS = [{ id: "4000-2", name: "4000词-2", wordCount: 599 }]

// 收藏本初始数据 - 与我的书架相同
const INITIAL_FAVORITE_BOOKS = [{ id: "4000-2", name: "4000词-2", wordCount: 599 }]

export default function BooksScreen() {
    const router = useRouter()
    const params = useLocalSearchParams()
    const [activeTab, setActiveTab] = useState("library") // library, shelf, favorite
    const [activeCategory, setActiveCategory] = useState("hot")
    const [myBooks, setMyBooks] = useState(INITIAL_MY_BOOKS)
    const [favoriteBooks, setFavoriteBooks] = useState(INITIAL_FAVORITE_BOOKS)
    const categoryScrollRef = useRef(null)

    // 判断是否来自计划页面
    const isFromPlan = params.source === "plan"
    const isPlanBookSelection = params.mode === "select_plan_book"

    const handleBack = () => {
        router.back()
    }

    const handleAddToBookshelf = (book) => {
        // 检查是否已存在
        if (!myBooks.some((b) => b.id === book.id)) {
            setMyBooks([...myBooks, book])
        }
    }

    const handleAddToFavorites = (book) => {
        // 检查是否已存在
        if (!favoriteBooks.some((b) => b.id === book.id)) {
            setFavoriteBooks([...favoriteBooks, book])
        }
    }

    const handleDeleteBook = (bookId) => {
        setMyBooks(myBooks.filter((book) => book.id !== bookId))
    }

    // 处理选择书籍
    const handleSelectBook = async (book) => {
        try {
            if (isPlanBookSelection) {
                // 如果是计划书本选择模式，保存为计划书本
                await AsyncStorage.setItem("selectedPlanBook", JSON.stringify(book))
                console.log("计划书籍已选择并存储:", book)

                Alert.alert(
                    "书籍已选择",
                    `已选择 "${book.title}" 作为计划书籍，正在返回计划页面`,
                    [{ text: "确定", onPress: () => router.back() }],
                    { cancelable: false },
                )
            } else {
                // 否则，保存为单词本书籍
                await AsyncStorage.setItem("selectedBook", JSON.stringify(book))
                console.log("书籍已选择并存储:", book)

                Alert.alert(
                    "书籍已选择",
                    `已选择 "${book.title}"，正在返回单词本页面`,
                    [{ text: "确定", onPress: () => router.back() }],
                    { cancelable: false },
                )
            }
        } catch (error) {
            console.error("保存选中书籍数据失败:", error)
            // 即使存储失败，也返回上一页
            router.back()
        }
    }

    // 滚动到选中的分类
    useEffect(() => {
        if (categoryScrollRef.current && activeTab === "library") {
            const index = CATEGORIES.findIndex((cat) => cat.id === activeCategory)
            if (index !== -1) {
                categoryScrollRef.current.scrollTo({
                    x: index * 80, // 估计每个分类项的宽度
                    animated: true,
                })
            }
        }
    }, [activeCategory, activeTab])

    return (
        <GestureHandlerRootView style={styles.container}>
            <StatusBar barStyle="dark-content" />

            {/* 头部 - 使用渐变背景 */}
            <LinearGradient
                colors={["#D8E4FF", "#EEF3FF"]}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={styles.headerGradient}
            >
                <SafeAreaView edges={["top"]} style={styles.safeAreaHeader}>
                    {/* 头部布局 */}
                    <View style={styles.headerLayout}>
                        {/* 返回按钮 - 放在最左侧 */}
                        <TouchableOpacity onPress={handleBack} style={styles.backButton}>
                            <ArrowLeft size={24} color={theme.colors.neutral.black} />
                        </TouchableOpacity>

                        {/* 选项卡 - 居中 */}
                        <View style={[styles.tabContainer, isFromPlan ? styles.tabContainerWithFavorite : null]}>
                            <TouchableOpacity
                                style={[styles.tab, activeTab === "library" && styles.activeTab]}
                                onPress={() => setActiveTab("library")}
                            >
                                <Text style={[styles.tabText, activeTab === "library" && styles.activeTabText]}>辞书库</Text>
                            </TouchableOpacity>

                            <TouchableOpacity
                                style={[styles.tab, activeTab === "shelf" && styles.activeTab]}
                                onPress={() => setActiveTab("shelf")}
                            >
                                <Text style={[styles.tabText, activeTab === "shelf" && styles.activeTabText]}>我的书架</Text>
                            </TouchableOpacity>

                            {isFromPlan && (
                                <TouchableOpacity
                                    style={[styles.tab, activeTab === "favorite" && styles.activeTab]}
                                    onPress={() => setActiveTab("favorite")}
                                >
                                    <View style={styles.favoriteTabContent}>
                                        <BookmarkIcon
                                            size={14}
                                            color={activeTab === "favorite" ? theme.colors.primary.default : theme.colors.neutral.gray}
                                        />
                                        <Text style={[styles.tabText, activeTab === "favorite" && styles.activeTabText]}>收藏本</Text>
                                    </View>
                                </TouchableOpacity>
                            )}
                        </View>

                        {/* 占位视图 - 保持布局平衡 */}
                        <View style={styles.placeholderView} />
                    </View>

                    {/* 分类导航 - 仅在辞书库时显示 */}
                    {activeTab === "library" && (
                        <ScrollView
                            ref={categoryScrollRef}
                            horizontal
                            showsHorizontalScrollIndicator={false}
                            contentContainerStyle={styles.categoryScrollContent}
                        >
                            {CATEGORIES.map((category) => (
                                <TouchableOpacity
                                    key={category.id}
                                    style={[styles.categoryItem, activeCategory === category.id && styles.activeCategoryItem]}
                                    onPress={() => setActiveCategory(category.id)}
                                >
                                    <Text style={[styles.categoryText, activeCategory === category.id && styles.activeCategoryText]}>
                                        {category.name}
                                    </Text>
                                    {activeCategory === category.id && <View style={styles.categoryIndicator} />}
                                </TouchableOpacity>
                            ))}
                        </ScrollView>
                    )}
                </SafeAreaView>
            </LinearGradient>

            {/* 内容区域 */}
            {activeTab === "library" ? (
                <LibraryContent
                    activeCategory={activeCategory}
                    onAddToBookshelf={handleAddToBookshelf}
                    onAddToFavorites={isFromPlan ? handleAddToFavorites : undefined}
                    onSelectBook={handleSelectBook}
                    isPlanMode={isPlanBookSelection}
                />
            ) : activeTab === "shelf" ? (
                <BookshelfView
                    books={myBooks}
                    onDeleteBook={handleDeleteBook}
                    onSelectBook={handleSelectBook}
                    allowDelete={!isFromPlan} // 如果来自计划页面，不允许删除
                />
            ) : (
                <BookshelfView
                    books={favoriteBooks}
                    onDeleteBook={() => { }} // 收藏本不允许删除
                    onSelectBook={handleSelectBook}
                    allowDelete={false}
                    emptyMessage="收藏本中还没有书籍"
                    emptyDescription="从辞书库中添加你喜欢的书籍到收藏本"
                />
            )}
        </GestureHandlerRootView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.background,
    },
    // 新的头部样式
    headerGradient: {
        width: "100%",
    },
    safeAreaHeader: {
        width: "100%",
    },
    // 头部布局 - 使用flexDirection: "row"
    headerLayout: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingVertical: theme.spacing.md,
        paddingHorizontal: theme.spacing.lg,
    },
    // 返回按钮 - 放在最左侧
    backButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "rgba(255, 255, 255, 0.5)",
    },
    // 选项卡 - 居中
    tabContainer: {
        width: 200,
        flexDirection: "row",
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        borderRadius: theme.borderRadius.large,
        padding: theme.spacing.xs,
    },
    tabContainerWithFavorite: {
        width: 280, // 增加宽度以容纳第三个选项卡
    },
    tab: {
        flex: 1,
        paddingVertical: theme.spacing.sm,
        alignItems: "center",
        borderRadius: theme.borderRadius.medium,
    },
    activeTab: {
        backgroundColor: theme.colors.neutral.white,
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 1 },
                shadowOpacity: 0.3,
                shadowRadius: 2,
            },
            android: {
                elevation: 2,
            },
        }),
    },
    tabText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        fontWeight: theme.fontWeight.medium,
    },
    activeTabText: {
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    favoriteTabContent: {
        flexDirection: "row",
        alignItems: "center",
        gap: 4,
    },
    // 占位视图 - 保持布局平衡
    placeholderView: {
        width: 40,
    },
    // 分类导航样式
    categoryScrollContent: {
        paddingHorizontal: theme.spacing.lg,
        paddingBottom: theme.spacing.lg,
        paddingTop: theme.spacing.sm,
    },
    categoryItem: {
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.sm,
        marginRight: theme.spacing.md,
        position: "relative",
        minWidth: 60,
        alignItems: "center",
    },
    categoryText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        fontWeight: theme.fontWeight.medium,
    },
    activeCategoryText: {
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.semiBold,
    },
    categoryIndicator: {
        position: "absolute",
        bottom: 0,
        left: "25%",
        right: "25%",
        height: 3,
        backgroundColor: theme.colors.primary.default,
        borderRadius: 1.5,
    },
})

